﻿Imports System.Data.SqlClient

Public Class xtf_LISTADOinformeCuota_
    Public WithEvents dtt_DataTable As New DataTable
    Public PERMISOImprimir As String = ""


#Region "Total registros ..."

    Private Sub gdv_general_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdv_general.RowCountChanged
        Dim Total As Decimal
        For Each row As DataRow In dtt_DataTable.Rows
            Total += row("importe")
        Next
        bsi_registros.Caption = "Total Cuotas Listadas: " & gdv_general.RowCount & "  Importe Total: " & Math.Round(Total, int_cantdecimales)
    End Sub

#End Region

#Region "General"
    Private Sub bbi_cerrar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_cerrar.ItemClick
        Me.Close()
    End Sub

    Private Sub btn_Cerrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Cerrar.Click
        Me.Close()
    End Sub

    Private Sub bbi_actualizar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_actualizar.ItemClick
        dtt_DataTable = New DataTable
        IniciarLista()
    End Sub

    Private Sub xtf_Listado_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        guardar_config_usuariocolumna_()
    End Sub

    Private Sub guardar_config_usuariocolumna_()
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(UsuarioLOG.idusuario, Me.Name) Then
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.Modificar()
        Else
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.idusuario = UsuarioLOG.idusuario
            obj_config_usuariocolumna_.modulo = Me.Name
            obj_config_usuariocolumna_.Nuevo()
        End If
    End Sub

    Public Sub FiltrarColumnas()
        Dim int_IDUsuario As Integer = UsuarioLOG.idusuario
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        gdv_general.BeginUpdate()
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(int_IDUsuario, Me.Name) Then
            SetLayoutData(gdv_general, obj_config_usuariocolumna_.xml)
        End If

        PerzonalizarControl(gdc_general)

        gdv_general.EndUpdate()
    End Sub

    Private Function GetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView) As Byte()
        Dim stream As New System.IO.MemoryStream()
        prm_GridView.SaveLayoutToStream(stream)
        Return stream.GetBuffer()
    End Function

    Private Sub SetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView, ByVal data As Byte())
        If data Is Nothing OrElse data.Length = 0 Then
            Return
        End If
        Dim stream As New System.IO.MemoryStream(data)
        Try
            prm_GridView.RestoreLayoutFromStream(stream)
        Catch ex As Exception
            Throw New Exception("Wrong data format", ex)
        End Try
    End Sub

    Private Sub bbi_columnas_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_columnas.ItemClick
        gdv_general.ColumnsCustomization()
    End Sub
#End Region

    Public Sub New()

        Me.Cursor = Cursors.WaitCursor
        InitializeComponent()
        PERMISOImprimir = "002002005"
        lbl_modulo.Text = "Informe de Cuotas"
        Me.Text = lbl_modulo.Text : lbl_modulodescripcion.Text = "Listado de " & lbl_modulo.Text & "."
        IniciarLista()
        Me.Cursor = Cursors.Default

        dtp_fechaDesde.DateTime = Now
        cbo_cuotas.SelectedIndex = 0

        Dim desde As DateTime = New Date(Now.Year, Now.Month, 1)
        Dim hasta As DateTime = DateAdd(DateInterval.Day, -1, DateAdd(DateInterval.Month, 1, desde))
        dtp_fechaDesde.DateTime = desde
        dtp_fechaHasta.DateTime = hasta

        Dim vendedores As New cls_vendedor_
        vendedores.CargarTodos()
        cargarCombo(cbo_vendedor, vendedores.Items)
        cbo_vendedor.Enabled = False
    End Sub

    Public Sub IniciarLista()
        Try
            gdc_general.BeginUpdate()
            dtt_DataTable = New DataTable

            gdc_general.DataSource = dtt_DataTable
            'ulg_Lista.DisplayLayout.GroupByBox.Style = Infragistics.Win.UltraWinGrid.GroupByBoxStyle.Full

            dtt_DataTable.Columns.Add("cia")
            dtt_DataTable.Columns.Add("asegurado")
            dtt_DataTable.Columns.Add("nueva")
            dtt_DataTable.Columns.Add("pza")
            dtt_DataTable.Columns.Add("importe")
            dtt_DataTable.Columns.Add("numero")
            dtt_DataTable.Columns.Add("total")
            dtt_DataTable.Columns.Add("obs")
            dtt_DataTable.Columns.Add("observaciones")

            'Dim obj_Personal_ As New cls_personal_
            'If obj_Personal_.CargarTodos() Then
            '    For Each Personal As cls_personal_ In obj_Personal_.Items
            '        AgregarItem(Personal)
            '    Next
            'End If
            'gdv_general.PopulateColumns()
            FiltrarColumnas()
            gdv_general.BestFitColumns()
            gdc_general.EndUpdate()
        Catch ex As Exception
            'Dim frmError As New frm_ErrorManager(ex.Message)
        End Try
    End Sub
    Public Sub AgregarItem(ByRef cuota As cls_cuota_)
        Dim Row As DataRow = dtt_DataTable.NewRow
        If Not IsNothing(cuota.poliza.proveedor) Then
            Row("cia") = cuota.poliza.proveedor.codigo
        End If
        If Not IsNothing(cuota.poliza.cliente) Then
            Row("asegurado") = cuota.poliza.cliente.tercero.nombres
        End If

        If cuota.poliza.nueva Then
            Row("nueva") = "Si"
        Else
            Row("nueva") = ""
        End If
        Row("pza") = cuota.importe
        Row("importe") = Math.Round(cuota.importe, int_cantdecimales)
        Row("numero") = cuota.numero
        Row("total") = cuota.total
        Row("obs") = cuota.Obs
        Row("observaciones") = cuota.Observaciones

        dtt_DataTable.Rows.Add(Row)
        'ulg_Lista.Rows(ulg_Lista.Rows.Count - 1) = Persona.Height = 19
    End Sub

    Public Sub btn_buscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_buscar.Click
        dtt_DataTable.Rows.Clear()
        Dim obj_cuota_ As New cls_cuota_
        Dim desde As DateTime = New Date(dtp_fechaDesde.DateTime.Year, dtp_fechaDesde.DateTime.Month, dtp_fechaDesde.DateTime.Day, 0, 0, 0)
        Dim hasta As DateTime = New Date(dtp_fechaHasta.DateTime.Year, dtp_fechaHasta.DateTime.Month, dtp_fechaHasta.DateTime.Day, 23, 59, 59)
        If obj_cuota_.CargarXFecha(desde, hasta) Then
            For Each cuota As cls_cuota_ In obj_cuota_.Items
                AgregarItem(cuota)
            Next
        End If
    End Sub

    'Public Sub btn_limpiar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    dtt_DataTable.Rows.Clear()
    '    txt_buscarAgrupacion.Text = ""
    '    txt_buscarCategoria.Text = ""
    '    txt_buscarContacto.Text = ""
    '    txt_buscarDireccion.Text = ""
    '    txt_buscarLocalidad.Text = ""
    '    txt_buscarNombre.Text = ""
    '    txt_buscarObservaciones.Text = ""
    '    txt_buscarOtros.Text = ""
    '    txt_buscarTelefono.Text = ""
    'End Sub

    Private Sub btn_exportarImprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_exportarImprimir.Click
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEcuota_ = generarReporte()
            report.ShowPreview()
        End If
    End Sub


    Public Sub bbi_imprimir_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_imprimir.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEcuota_ = generarReporte()
            Try
                report.Print()
            Catch ex As Exception
                ErrManagerShow("Error inesperado.", ex.Message, xtf_ErrManagerAlerta.errManagerImg.img_Error, xtf_ErrManagerAlerta.errManagerBtn.btn_SalirDelSistema)
            End Try
        End If
    End Sub

    Public Sub bbi_exportarPDF_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarPDF.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEcuota_ = generarReporte()

            Dim SAVEFILE As New SaveFileDialog
            SAVEFILE.Filter = "PDF (*.PDF)|*.PDF"
            SAVEFILE.FilterIndex = 2
            If SAVEFILE.ShowDialog() = DialogResult.OK Then
                report.ExportToPdf(SAVEFILE.FileName)
            End If
        End If
    End Sub

    Public Sub bbi_vistaprevia_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_vistaprevia.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEcuota_ = generarReporte()
            report.ShowPreview()
        End If
    End Sub

    Public Sub bbi_exportarExcel_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarExcel.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtr_REPORTEcuota_ = generarReporte()
            Dim SAVEFILE As New SaveFileDialog
            SAVEFILE.Filter = "XLS (*.XLS)|*.XLS"
            SAVEFILE.FilterIndex = 2
            If SAVEFILE.ShowDialog() = DialogResult.OK Then
                report.ExportToXls(SAVEFILE.FileName)
            End If
        End If
    End Sub

    Private Function generarReporte() As xtr_REPORTEcuota_

        Dim report As New xtr_REPORTEcuota_
        report.DataSource = gdc_general.DataSource
        If dtp_fechaDesde.DateTime.Month = dtp_fechaHasta.DateTime.Month And dtp_fechaDesde.DateTime.Year = dtp_fechaHasta.DateTime.Year Then
            report.lbl_informe.Text = "Informe de Cuotas : " & Format(dtp_fechaHasta.DateTime, "MMMM") & " " & dtp_fechaHasta.DateTime.Year & " (" & dtp_fechaDesde.DateTime.Day & " al " & dtp_fechaHasta.DateTime.Day & ")"
        Else
            report.lbl_informe.Text = "Informe de Cuotas : " & dtp_fechaDesde.DateTime.ToShortDateString & " al " & dtp_fechaHasta.DateTime.ToShortDateString
        End If
        Dim Total As Decimal
        For Each row As DataRow In dtt_DataTable.Rows
            Total += row("importe")
        Next
        report.lbl_totalimporte.Text = "Total Cuotas Listadas : " & gdv_general.RowCount
        report.lbl_totalcuotas.Text = "Importe Total : " & Math.Round(Total, 2)

        Return report
    End Function
End Class